const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('./util/logHelper').helper;
const cors = require('koa2-cors');
const koaStatic = require('koa-static');
const commonUtils = require('./util/commonUtils');
const adminService=require('./service/adminService');

const index = require('./routes/index');
const users = require('./routes/users');
const corporation = require('./routes/corporation');
const login = require('./routes/login');
const file = require('./routes/file');
const cases = require('./routes/case');
const service = require('./routes/service');
const category = require('./routes/category');
const addAdvert = require('./routes/advert');
const appointment = require('./routes/appointment');

const goods = require('./wxApi/routes/service');
const wxCorporation = require('./wxApi/routes/corporation');
const wxCategory = require('./wxApi/routes/category');
const wxCase = require('./wxApi/routes/case');
const wxAdvert = require('./wxApi/routes/advert');
const wxLogin = require('./wxApi/routes/login');

// error handler
onerror(app);
// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}));
app.use(json());

app.use(require('koa-static')(__dirname + '/public'));

app.use(koaStatic(__dirname + '/data/uploads/image'));
app.use(views(__dirname + '/views', {
    extension: 'pug'
}));
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
            return false;
        }
        return '*';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', ' X-Requested-With']
}));

//logger,请求开始和结束时的日志
app.use(async (ctx, next) => {
    //get每个请求带上唯一的id，查日志方便查看哪个请求开始对应哪个请求结束
    let requestId = commonUtils.genUUID();
    let requestBody = commonUtils.toMyString(ctx.request.body);

    //请求进来时打印日志
    logger.writeInfo(`--> ${ctx.method} ${ctx.url} requestId=${requestId} start body=${requestBody} requestId=${requestId}`);
    const start = new Date();
    await next();
    const ms = new Date() - start;
    let responseBody = commonUtils.toMyString(ctx.body);
    //请求结束时打印日志
    logger.writeInfo(`--> ${ctx.method} ${ctx.url} requestId=${requestId} end responseBody=${responseBody} -${ms}ms`);
});

//拦截器
/*
let ex=['/api/admin/login','/api/file/upload','/api/file/uploadMain'];
app.use(async(ctx,next)=>{
    let url=ctx.url;
    const urlReg=new RegExp('/api/*');
    if(urlReg.test(url)){
        let urls=url.split("?");
        let index=ex.indexOf(urls[0]);
        if(index===-1){
            let token=ctx.request.body.token||ctx.query.token;
            let data={token:token};
            if(token){
                try{
                    let re;
                    re=await adminService.queryAdminByToken(data);
                    if(re.length===0){
                        ctx.body={code:-1,msg:'token没有找到'};
                        return;
                    }else{
                        ctx.request.body.username=re[0].username;
                        await next();
                        return;
                    }
                }catch (e){
                    ctx.body={code:0,msg:e.message};
                    return;
                }
            }else{
                ctx.body={code:-1,msg:'token没有找到'};
                return;
            }
        }
    }
    await next();
});
*/


// logger
app.use(async (ctx, next) => {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(corporation.routes(), corporation.allowedMethods());
app.use(login.routes(), login.allowedMethods());
app.use(file.routes(), file.allowedMethods());
app.use(cases.routes(), cases.allowedMethods());
app.use(service.routes(), service.allowedMethods());
app.use(category.routes(), category.allowedMethods());
app.use(addAdvert.routes(), addAdvert.allowedMethods());
app.use(appointment.routes(), appointment.allowedMethods());

app.use(goods.routes(), goods.allowedMethods());
app.use(wxCorporation.routes(), wxCorporation.allowedMethods());
app.use(wxCategory.routes(), wxCategory.allowedMethods());
app.use(wxCase.routes(), wxCase.allowedMethods());
app.use(wxAdvert.routes(), wxAdvert.allowedMethods());
app.use(wxLogin.routes(), wxAdvert.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
});

module.exports = app;
